package com.southwind.phone_store_demohd.service.impl;


import com.southwind.phone_store_demohd.entity.BuyerAddress;
import com.southwind.phone_store_demohd.form.AddressForm;
import com.southwind.phone_store_demohd.repository.BuyerAddressRepsitory;
import com.southwind.phone_store_demohd.service.AddressService;
import com.southwind.phone_store_demohd.vo.AddressVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private BuyerAddressRepsitory buyerAddressRepsitory;

    //查询全部的地址（用户直接显示地址）
    @Override
    public List<AddressVO> findAll() {

        //查询出全部地址
        List<AddressVO> list = buyerAddressRepsitory.findAll().stream()
                .map(e -> new AddressVO(
                        e.getAddressId(),
                        e.getAreaCode(),
                        e.getBuyerName(),
                        e.getBuyerPhone(),
                        e.getBuyerAddress()
                )).collect(Collectors.toList());

        return list;
    }



    //传递一个详细地址（修改地址）
    //这个方法把添加和修改写在一起了，用判断有没有id这个值来进行增加还是修改
    @Override
    public void saveOrUpdate(AddressForm addressForm) {
        BuyerAddress buyerAddress;//判断这个地址模型里面有没有id
        if(addressForm.getId() == null){
            //id为空的话就是增加，直接创建地址模型对象，给数据
            buyerAddress = new BuyerAddress();
        } else {
            //id不为空的话就是修改，根据前端传递过来的id对相应的数据进行数据库修改
            buyerAddress = buyerAddressRepsitory.findById(addressForm.getId()).get();
        }
        //把前端用户输入的数据传递给地址模型
        buyerAddress.setBuyerName(addressForm.getName());
        buyerAddress.setBuyerPhone(addressForm.getTel());
        StringBuffer stringBuffer = new StringBuffer();
        //这里是把地址相加起来
        stringBuffer.append(addressForm.getProvince())
                .append(addressForm.getCity())
                .append(addressForm.getCounty())
                .append(addressForm.getAddressDetail());
        buyerAddress.setBuyerAddress(stringBuffer.toString());
        buyerAddress.setAreaCode(addressForm.getAreaCode());

        buyerAddressRepsitory.save(buyerAddress);//传递给数据库
    }
}
